package com.atguigu.gmall.user.controller;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Mamba
 * @version 1.0
 * @Description
 * @date 2021/1/3 16:46
 */
@RestController
@RequestMapping("/api/user/passport")
public class LoginApiController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;

//登录
    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo){
        //1:判断用户名是否为NULL  空
        //2:判断密码是否为NULL 空
        //3:查询DB 校验用户名密码 是否正确
      userInfo = loginService.login(userInfo);
      if (null != userInfo){
          Map result = new HashMap();
          //传统 token UUID36位 4个小横线
          String uuid = UUID.randomUUID().toString().replaceAll("-", "");
          result.put("token",uuid);
          //昵称
          result.put("nickName",userInfo.getNickName());
          //保存Redis一份
          redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+uuid,
                  userInfo.getId().toString(),30, TimeUnit.DAYS);
          return Result.ok(result);
      }else {
          return Result.fail().message("用户名或密码错误");
      }
    }
//退出登录
    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
        return Result.ok();
    }

}
